<?php
namespace Frieza\Modules\Totem\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Member;
use Doraemon\model\Totem\TotemTypes;
use Doraemon\service\Totem\TotemService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Form;
use Illuminate\Support\MessageBag;
use Doraemon\tools\Log;

class TotemTypeController extends Controller
{
    const CHANNEL_TAGS_FILE = '/home/adm_rsync_dir/question_hot_tags_for_search.json';

    public function typeList(Request $request, Content $content)
    {
        $params = $request->input();
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $search = [];
        $list = TotemService::getTypeList($page, $pageSize, $search);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->column("id", 'ID');
                $grid->column("type_name", '名称');
                $grid->column("user_type", '用户身份')->display(function () {
                    $this->user_type = array_map(function ($user_type){
                        return Member::$totemUserType[$user_type];
                    }, $this->user_type);
                    return $this->user_type;
                })->label()->width(300);
                $grid->column("group_id", '分类')->using(TotemTypes::GROUP_DESC);
                $grid->column('alone_group', '是否属于二级分类')->using(TotemTypes::ALONE_GROUP)->label([
                    TotemTypes::ALONE_GROUP_NO => 'default',
                    TotemTypes::ALONE_GROUP_YES => 'info'
                ]);
                $grid->column("addtime", '创建时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->addtime);
                });
                $grid->column("edittime", '更新时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->edittime);
                });
                $grid->column("admin_id", '操作人员')->display(function () {
                    return "<span style='width:80px;display: inline-block;'>".Admin::user()->find($this->admin_id)->name."</span>";
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                });
            });

        $tab = new Tab();
        $tab->add('类型列表', $gridList->render(), true);
        $tab->addLink('添加类型', url('admin/totem/type_create'));
        $content->row($tab);
        return $content
            ->header('徽章类型管理')
            ->description(' ')
            ->breadcrumb(['text' => '类型列表']);
    }

    public function typeCreate(Request $request, Content $content, $id = 0)
    {
        $row = [];
        if ($id) {
            $row = TotemService::getTypeInfo($id);
            $header = "编辑类型";
        } else {
            $header = "添加类型";
        }
        $tab = new Tab();
        $form = new Form($row);

        if ($id) {
            $form->hidden('id');
        }
        $form->text('type_name', '类型名')->required();
        $form->multipleSelect('user_type', '用户身份')->options(Member::$totemUserType)->help("只有所选用户身份下的用户可以看到该类型的徽章！")->required();
        $form->radio('group_id', '分类')
            ->options(TotemTypes::GROUP_DESC)
            ->default(TotemTypes::GROUP_GROWING)
            ->when(TotemTypes::GROUP_GROWING, function (Form $form) {
            })->when(TotemTypes::GROUP_FIELD, function (Form $form) {
                $form->select('unlock_type', '解锁任务类型')
                    ->options(TotemTypes::UNLOCK_TYPE_DESC)
                    ->when(TotemTypes::UNLOCK_TYPE_NOTE, function (Form $form)  {
                        $channel_tags = [];
                        if(file_exists(self::CHANNEL_TAGS_FILE)) {
                            $channel_tags_base = json_decode(file_get_contents(self::CHANNEL_TAGS_FILE), true);
                            if($channel_tags_base && is_array($channel_tags_base)) {
                                foreach($channel_tags_base as $channel_tag) {
                                    $channel_tags[$channel_tag] = $channel_tag;
                                }
                            }
                        }
                        $form->select('unlock_params', '解锁参数')->options($channel_tags);
                    });
            })->when(TotemTypes::GROUP_LIMIT, function (Form $form) {
            });
        $form->radio('alone_group', '是否属于二级分类')->options(TotemTypes::ALONE_GROUP)->default(TotemTypes::ALONE_GROUP_NO);

        $form->action(url('admin/totem/type_save'));

        $tab->addLink('类型列表', url('admin/totem/type_list'));
        $tab->add($header, $form->render(), true);
        return $content
            ->header('徽章类型管理')
            ->description(' ')
            ->breadcrumb(['text' => $header])
            ->row($tab);
    }

    public function typeSave(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $result = TotemService::saveType($params);
            if ($result) {
                return redirect(url('/admin/totem/type_list'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }
}